"""算法注册表 - 管理所有可用算法

提供算法的注册、获取和列表功能，支持动态扩展算法库。
算法按类别组织：预处理器、峰值检测器、指标计算器、质量评估器。
"""

from typing import Dict, Callable, Any, List
import logging

# 配置日志
logger = logging.getLogger(__name__)

# 算法注册表
ALGORITHM_REGISTRY: Dict[str, Dict[str, Callable]] = {
    'preprocessors': {},      # 预处理算法
    'peak_detectors': {},     # 峰值检测算法
    'metrics_calculators': {},# 指标计算算法
    'quality_assessors': {}   # 质量评估算法
}

def register_algorithm(category: str, name: str, function: Callable) -> None:
    """注册算法函数
    
    Args:
        category: 算法类别 ('preprocessors', 'peak_detectors', 'metrics_calculators', 'quality_assessors')
        name: 算法名称
        function: 算法函数
        
    Raises:
        ValueError: 当算法类别未知时
        
    Example:
        >>> def my_preprocessor(data, sampling_rate):
        ...     return processed_data
        >>> register_algorithm('preprocessors', 'my_algo', my_preprocessor)
    """
    if category not in ALGORITHM_REGISTRY:
        available_categories = list(ALGORITHM_REGISTRY.keys())
        raise ValueError(f"未知的算法类别: {category}. 可用类别: {available_categories}")
    
    if name in ALGORITHM_REGISTRY[category]:
        logger.warning(f"算法 {name} 已存在于类别 {category} 中，将被覆盖")
    
    ALGORITHM_REGISTRY[category][name] = function
    logger.info(f"成功注册算法: {category}.{name}")

def get_algorithm(category: str, name: str) -> Callable:
    """获取算法函数
    
    Args:
        category: 算法类别
        name: 算法名称
        
    Returns:
        算法函数
        
    Raises:
        ValueError: 当算法类别或名称不存在时
        
    Example:
        >>> preprocessor = get_algorithm('preprocessors', 'basic')
        >>> result = preprocessor(data, sampling_rate=4)
    """
    if category not in ALGORITHM_REGISTRY:
        available_categories = list(ALGORITHM_REGISTRY.keys())
        raise ValueError(f"未知的算法类别: {category}. 可用类别: {available_categories}")
    
    if name not in ALGORITHM_REGISTRY[category]:
        available_algorithms = list(ALGORITHM_REGISTRY[category].keys())
        raise ValueError(f"算法 {name} 未在类别 {category} 中注册. 可用算法: {available_algorithms}")
    
    return ALGORITHM_REGISTRY[category][name]

def list_available_algorithms() -> Dict[str, List[str]]:
    """列出所有可用算法
    
    Returns:
        按类别组织的算法名称字典
        
    Example:
        >>> algorithms = list_available_algorithms()
        >>> print(algorithms['preprocessors'])
        ['basic', 'improved', 'neurokit2']
    """
    return {
        category: list(algorithms.keys()) 
        for category, algorithms in ALGORITHM_REGISTRY.items()
    }

def get_algorithm_count() -> Dict[str, int]:
    """获取各类别算法数量统计
    
    Returns:
        各类别算法数量字典
    """
    return {
        category: len(algorithms)
        for category, algorithms in ALGORITHM_REGISTRY.items()
    }

def is_algorithm_registered(category: str, name: str) -> bool:
    """检查算法是否已注册
    
    Args:
        category: 算法类别
        name: 算法名称
        
    Returns:
        是否已注册
    """
    return (category in ALGORITHM_REGISTRY and 
            name in ALGORITHM_REGISTRY[category])

def unregister_algorithm(category: str, name: str) -> bool:
    """注销算法
    
    Args:
        category: 算法类别
        name: 算法名称
        
    Returns:
        是否成功注销
    """
    if not is_algorithm_registered(category, name):
        logger.warning(f"尝试注销不存在的算法: {category}.{name}")
        return False
    
    del ALGORITHM_REGISTRY[category][name]
    logger.info(f"成功注销算法: {category}.{name}")
    return True

def get_algorithm_info() -> Dict[str, Any]:
    """获取算法注册表详细信息
    
    Returns:
        包含算法统计和详细信息的字典
    """
    info = {
        'total_algorithms': sum(len(algs) for algs in ALGORITHM_REGISTRY.values()),
        'categories': list(ALGORITHM_REGISTRY.keys()),
        'algorithm_count_by_category': get_algorithm_count(),
        'algorithms_by_category': list_available_algorithms()
    }
    
    return info